//
//  HBBondListCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/12/3.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBBondListCtrl.h"
#import "HBBondListTotalCell.h"
#import "HBBoundListDesCell.h"
#import "HBBondListHeaderCell.h"
#import "HBBondListCell.h"
#import "HBBondListNoMoreCell.h"
#import "HBBondListHeaderView.h"
#import "HBBondListProtocolCell.h"
#import "MJRefresh.h"
#import "HBBondDetailCtrl.h"
#import "HBBondListProtocolCtrl.h"

#import "HBGetUserLoanContractInfo.h"
#import "HBGetUserLoanContractItemInfo.h"
#import "HBGetUserLoanContractParam.h"
#import "HBGetUserLoanContractParser.h"


@interface HBBondListCtrl ()
<UITableViewDataSource,
UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIImageView *emptyIV;

@property (nonatomic) int pageNum;

@property (nonatomic, strong) HBGetUserLoanContractInfo *contractInfo;


@end

@implementation HBBondListCtrl

#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.view.backgroundColor = [LCCommon getColor:@"e1e1e1"];
}

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"债权列表";
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    INIT_TABLE(_tableView);
    
    self.tableView.backgroundColor = [LCCommon getColor:Main_BackGround_Color];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 150, SCREEN_WIDTH, self.tableView.height-150)];
    bgView.backgroundColor = [LCCommon getColor:@"e1e1e1"];
    [self.tableView addSubview:bgView];
    [self.tableView sendSubviewToBack:bgView];
    
    __weak UITableView *tableView = self.tableView;
    __weak typeof(self) weakSelf = self;
    
    // 下拉刷新
    tableView.mj_header = [HBOrangeHeader headerWithRefreshingBlock:^{
        
        [weakSelf hideEmptyIV];
        weakSelf.pageNum = 1;
        [weakSelf requestToGetBondList];
        
        if (tableView.mj_footer)
        {
            [tableView.mj_footer resetNoMoreData];
        }
        
        //        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            // 结束刷新
        //            [tableView.mj_header endRefreshing];
        //        });
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        //        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            // 结束刷新
        //            [tableView.mj_footer endRefreshing];
        //        });
        
        if (weakSelf.contractInfo.dataAry.count>0)
        {
            weakSelf.pageNum++;
            [weakSelf requestToGetBondList];
        }
        else
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 结束刷新
                [tableView.mj_footer endRefreshing];
            });
        }
        
    }];
    
//    [self.tableView.mj_header beginRefreshing];
    
    self.pageNum = 1;
    [self requestToGetBondList];
}

#pragma mark - private

- (void)showEmptyIV
{
    self.emptyIV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"My_Bond_Empty"]];
    self.emptyIV.center = self.tableView.center;
//    self.emptyIV.y = self.tableView.y+Height_HBBondListTotalCell+65;
    self.emptyIV.y = (SCREEN_HEIGHT - 64 - Height_HBBondListTotalCell)/2-self.emptyIV.height/2+Height_HBBondListTotalCell;
    
    //    self.emptyIV.center = CGPointMake(self.emptyIV.center.x, self.tableView.y+Height_HBIncomeDetailTotalCell+65);
    [self.view addSubview:self.emptyIV];
    
}

- (void)hideEmptyIV
{
    [self.emptyIV removeFromSuperview];
    self.emptyIV = nil;
}

- (NSInteger)numberOfRowsInSection:(NSInteger)section
{
    if (section==0)
    {
        return 1;
    }
    else
    {
        if (section==1)
        {
            return 1;
        }
        else if(section==2)
        {
            return self.contractInfo.dataAry.count;
        }
        else
        {
            return 1;
        }

    }
}

- (NSString *)getCellIdentifierForIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        return NSStringFromClass([HBBondListTotalCell class]);
    }
    else if(indexPath.section==1)
    {
        return NSStringFromClass([HBBoundListDesCell class]);
    }
    else if(indexPath.section==2)
    {
        return NSStringFromClass([HBBondListCell class]);
    }
    else
    {
//        return NSStringFromClass([HBBondListNoMoreCell class]);
        return NSStringFromClass([HBBondListProtocolCell class]);
    }
}

- (CGFloat)heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        return Height_HBBondListTotalCell;
    }
    else if(indexPath.section==1)
    {
        return Height_HBBoundListDesCell;
    }
    else if(indexPath.section==2)
    {
        return Height_HBBondListCell;
    }
    else
    {
//        return Height_HBBondListNoMoreCell;
        return Height_HBBondListProtocolCell;
    }
}

- (void)uploadBondListTotalCell:(HBBondListTotalCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.totalIncome.text = self.totalMoney;
}

- (void)uploadBoundListDesCell:(HBBoundListDesCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)uploadBoundListCell:(HBBondListCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    HBGetUserLoanContractItemInfo *itemInfo = self.contractInfo.dataAry[indexPath.row];
    cell.nameLable.text = itemInfo.borrowerName;
    cell.moneyLable.text = itemInfo.loanMoney;
    cell.timeLable.text = itemInfo.loanDate;
}

- (void)uploadBoundListNoMoreCell:(HBBondListNoMoreCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)uploadBoundListProtocolCell:(HBBondListProtocolCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - tableView delegate&dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.contractInfo.dataAry.count>0)
    {
        return 4;
    }
    else
    {
        return 1;
    }
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self numberOfRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self getCellIdentifierForIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (indexPath.section==0)
    {
        if (!cell)
        {
            cell = [[HBBondListTotalCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else if(indexPath.section==1)
    {
        if (!cell)
        {
            cell = [[HBBoundListDesCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else if(indexPath.section==2)
    {
        if (!cell)
        {
            cell = [[HBBondListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        
    }
    else
    {
        if (!cell)
        {
//            cell = [[HBBondListNoMoreCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell = [[HBBondListProtocolCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    
    
    if (indexPath.section==0)
    {
        [self uploadBondListTotalCell:(HBBondListTotalCell *)cell atIndexPath:indexPath];
    }
    else if(indexPath.section==1)
    {
        [self uploadBoundListDesCell:(HBBoundListDesCell *)cell atIndexPath:indexPath];
        
    }
    else if(indexPath.section==2)
    {
        [self uploadBoundListCell:(HBBondListCell *)cell atIndexPath:indexPath];
    }
    else
    {
//        [self uploadBondListTotalCell:(HBBondListTotalCell *)cell atIndexPath:indexPath];
        [self uploadBoundListProtocolCell:(HBBondListProtocolCell *)cell atIndexPath:indexPath];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0||section==1||section==3)
    {
        return 0;
    }
    else
    {
        return Height_HBBondListHeaderView;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section!=0)
    {
        HBBondListHeaderView *view = [[HBBondListHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, Height_HBBondListHeaderView)];
        return view;
    }
    else
    {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self heightForRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==2)
    {
        HBGetUserLoanContractItemInfo *itemInfo = self.contractInfo.dataAry[indexPath.row];
        HBBondDetailCtrl *bondDetailCtrl = [[HBBondDetailCtrl alloc]init];
        bondDetailCtrl.contractItemInfo = itemInfo;
        [self.navigationController pushViewController:bondDetailCtrl animated:YES];
    }
    else if (indexPath.section==3)
    {
        HBBondListProtocolCtrl *bondDetailCtrl = [[HBBondListProtocolCtrl alloc]init];
        [self.navigationController pushViewController:bondDetailCtrl animated:YES];
    }
}

#pragma mark - net

- (void)requestToGetBondList
{
    [CustomLoadingView showHudToView:self.view];
    HBGetUserLoanContractParam *param = [[HBGetUserLoanContractParam alloc]init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.pageNum = [NSString stringWithFormat:@"%d",self.pageNum];
    HBGetUserLoanContractParser *parser = [[HBGetUserLoanContractParser alloc]init];
    [NetCenter getDataFromURL:Method_getUserLoanContract params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (self.pageNum==1)
        {
            [self.tableView.mj_header endRefreshing];
        }
        else
        {
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (myResult.code==0)
        {
            HBGetUserLoanContractInfo *listInfo = (HBGetUserLoanContractInfo *)myResult.result;
            if (self.pageNum==1)
            {
                self.contractInfo = listInfo;
                [self.tableView reloadData];
                if (self.contractInfo.dataAry.count==0)
                {
                    [self showEmptyIV];
                }
            }
            else
            {
                if (listInfo.dataAry.count>0)
                {
                    NSMutableArray *array = [NSMutableArray arrayWithArray:self.contractInfo.dataAry];
                    [array addObjectsFromArray:listInfo.dataAry];
                    self.contractInfo.dataAry = array;
                    [self.tableView reloadData];
                }
                else
                {
                    self.pageNum--;
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            //                self.msgListInfo = listInfo;
            //                [self.tableView reloadData];
        }
        else
        {
            DISSMISS_ERR(myResult.message);
            if (self.pageNum>1)
            {
                self.pageNum--;
            }
        }
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
        if (self.pageNum==1)
        {
            [self.tableView.mj_header endRefreshing];
        }
        else
        {
            [self.tableView.mj_footer endRefreshing];
            self.pageNum--;
        }
        
    }];
}


@end
